﻿using Absky.Business.OrganizationManage;
using Absky.Business.SystemManage;
using Absky.Entity.OrganizationManage;
using Absky.Entity.SystemManage;
using Absky.Enum;
using Absky.Model;
using Absky.Util;
using Absky.Model;
using Absky.Web.Operator;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace Absky.Web.Controllers
{
    /// <summary>
    /// 登录控制器
    /// </summary>
    public class LoginController : Controller
    {
        private readonly UserBLL userBLL = new UserBLL();
        private readonly LogLoginBLL logLoginBLL = new LogLoginBLL();
        /// <summary>
        /// 默认页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Default()
        {
            return RedirectToAction("Index", "Login");
        }
        /// <summary>
        /// 登录页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            if (GlobalContext.SystemConfig.Demo)
            {
                ViewBag.UserName = "admin";
                ViewBag.Password = "123456";
            }
            ViewBag.ErrorNum = await Operator.Operator.Instance.GetCurrentErrorNum();
            string absky_UItheme = CookieHelper.GetCookie("Absky_UItheme");
            //return absky_UItheme switch
            //{
            //    "1" => View("Index1"),
            //    "2" => View("Index2"),
            //    "3" => View("Index3"),
            //    "4" => View("Index4"),
            //    "5" => View("Index5"),
            //    _ => View("Index5")
            //};
            return View("Index5");
        }
        /// <summary>
        /// 退出登录
        /// 返回到登录页面
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> LoginOff()
        {
            #region 退出系统
            OperatorInfo user = await Operator.Operator.Instance.Current();
            if (user != null)
            {
                // 如果不允许同一个用户多次登录，当用户登出的时候，就不在线了
                if (!GlobalContext.SystemConfig.LoginMultiple)
                {
                    await userBLL.UpdateUser(new UserEntity { Id = user.UserId, IsOnline = 0 });
                }

                // 登出日志
                await logLoginBLL.SaveForm(new LogLoginEntity
                {
                    LogStatus = OperateStatusEnum.Success.ParseToInt(),
                    Remark = "退出系统",
                    IpAddress = NetHelper.Ip,
                    IpLocation = string.Empty,
                    Browser = NetHelper.Browser,
                    OS = NetHelper.GetOSVersion(),
                    ExtraRemark = NetHelper.UserAgent,
                    BaseCreatorId = user.UserId
                });

                Operator.Operator.Instance.RemoveCurrent();
                CookieHelper.RemoveCookie("RememberMe");
            }
            #endregion
            return View(nameof(Index));
        }
        #region 获取数据
        /// <summary>
        /// 获取验证码图片
        /// </summary>
        /// <returns></returns>
        public IActionResult GetCaptchaImage()
        {
            string sessionId = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>().HttpContext.Session.Id;

            Tuple<string, int> captchaCode = CaptchaHelper.GetCaptchaCode();
            byte[] bytes = CaptchaHelper.CreateCaptchaImage(captchaCode.Item1);
            SessionHelper.WriteSession("CaptchaCode", captchaCode.Item2);
            return File(bytes, @"image/jpeg");
        }
        #endregion
        #region 提交数据
        [HttpPost]
        public async Task<IActionResult> LoginJson(string userName, string password, string captchaCode)
        {
            var errorNum = await Operator.Operator.Instance.GetCurrentErrorNum();
            if(errorNum > 3)
            {
                if (string.IsNullOrEmpty(captchaCode))
                {
                    return Json(new LoginOutput { Code = ResultCodeEnum.Fail, Message = "验证码不能为空", ErrorNum = errorNum });
                }
                if (captchaCode != SessionHelper.GetSession("CaptchaCode").ParseToString())
                {
                    return Json(new LoginOutput{ Code = ResultCodeEnum.Fail, Message = "验证码错误，请重新输入", ErrorNum = errorNum });
                }
            }
            var loginOutput = new LoginOutput();
            Result<UserEntity> userObj = await userBLL.CheckLogin(userName, password, (int)PlatformEnum.Web);
            if (userObj.Code == ResultCodeEnum.Success)
            {
                Operator.Operator.Instance.ClearCurrentErrorNum();
                await new UserBLL().UpdateUser(userObj.Data);
                await Operator.Operator.Instance.AddCurrent(userObj.Data.WebToken);
                loginOutput.Code = ResultCodeEnum.Success;
                loginOutput.ErrorNum = 0;
            }
            else
            {
                await Operator.Operator.Instance.AddCurrentErrorNum();
                loginOutput.Code = ResultCodeEnum.Fail;
                loginOutput.Message = userObj.Message;
                loginOutput.ErrorNum = errorNum + 1;
            }

            string ip = NetHelper.Ip;
            string browser = NetHelper.Browser;
            string os = NetHelper.GetOSVersion();
            string userAgent = NetHelper.UserAgent;

            Action taskAction = async () =>
            {
                LogLoginEntity logLoginEntity = new LogLoginEntity
                {
                    LogStatus = userObj.Code == ResultCodeEnum.Success ? OperateStatusEnum.Success.ParseToInt() : OperateStatusEnum.Fail.ParseToInt(),
                    Remark = userObj.Message,
                    IpAddress = ip,
                    IpLocation = IpLocationHelper.GetIpLocation(ip),
                    Browser = browser,
                    OS = os,
                    ExtraRemark = userAgent,
                    BaseCreatorId = userObj.Data?.Id
                };

                // 让底层不用获取HttpContext
                logLoginEntity.BaseCreatorId ??= 0;

                await logLoginBLL.SaveForm(logLoginEntity);
            };
            AsyncTaskHelper.StartTask(taskAction);

            return Json(loginOutput);
        }
        #endregion
        /// <summary>
        /// 获取用户登录信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AuthorizeOnly, AjaxOnly]
        public async Task<IActionResult> GetUserInfo()
        {
            OperatorInfo userinfo = await Operator.Operator.Instance.Current();
            return Json(new Result<OperatorInfo>(ResultCodeEnum.Success, userinfo));
        }
    }
}
